package com.da.lon.wang.xlg.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.OrderInfoResultBean.Str_result;
import com.da.lon.wang.xlg.bean.OrderInfoResultBean.Value;

import java.util.ArrayList;

public class TakeGoodsChoiseAdapter extends BaseAdapter implements
        OnClickListener {
    Context context;
    ArrayList<Str_result> datas;
    LayoutInflater inflater;

    CallBack myCallBack;
    MyGridAdapter gridAdapter;
    double[] coordinates;

    public TakeGoodsChoiseAdapter(Context context, ArrayList<Str_result> datas,
                                  double[] coordinates, CallBack myCallBack) {
        this.context = context;
        this.datas = datas;
        inflater = LayoutInflater.from(context);
        this.myCallBack = myCallBack;
        this.coordinates = coordinates;
    }

    @Override
    public int getCount() {
        return datas != null ? datas.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return datas != null && datas.size() > position ? datas.get(position)
                : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            Holder holder = new Holder();
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.choise_take_tiem, null);
            }
            holder.choise_address = (TextView) convertView
                    .findViewById(R.id.choise_address);
            holder.choise_dist = (TextView) convertView
                    .findViewById(R.id.choise_dist);
            holder.choise_take = (Button) convertView
                    .findViewById(R.id.choise_take);
            holder.choise_take.setTag(position);
            holder.choise_shop_name = (TextView) convertView
                    .findViewById(R.id.choise_shop_name);
            holder.choise_location = (Button) convertView
                    .findViewById(R.id.choise_location);
            holder.choise_location.setTag(position);
            holder.choise_images = (GridView) convertView
                    .findViewById(R.id.choise_images);
            if (position < datas.size() && datas.get(position) != null
                    && datas.get(position).getValue() != null) {
                // 使用自定义的Adapter而不适用SimpleAdapter
                // 因为SimpleAdapter只能适配文字和文件 适配图片时会默认将图片识别为文件，会报“找不到文件”异常
                gridAdapter = new MyGridAdapter(datas.get(position).getValue(),
                        context);
                holder.choise_images.setAdapter(gridAdapter);
                // 动态设置GridView的高度，必须放在setAdapter之后，因为必须要保证Adapter不为空
                setListViewHeightBasedOnChildren(holder.choise_images);
                // 设置了高度之后需要重新刷新列表内部的数据
                gridAdapter.notifyDataSetChanged();

                Str_result data = datas.get(position);
                holder.choise_address.setText(data.getAddress());
                String dist = data.getDistance() != null ? data.getDistance() : "0";
                int dis = Integer.parseInt(dist);
                if (coordinates[0] == 0 && coordinates[1] == 0) {
                    holder.choise_dist.setText("定位失败");
                } else if (dis < 1000) {
                    holder.choise_dist.setText("距离" + dis + "米");
                } else {
                    holder.choise_dist.setText("距离" + dis / 1000 + "千米");
                }
                holder.choise_shop_name.setText(data.getName());
                holder.choise_take.setOnClickListener(this);
                holder.choise_location.setOnClickListener(this);
            }
            if (convertView.getTag() == null) {
                convertView.setTag(holder);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    /**
     * 动态获取gridView的总高度
     *
     * @param listView girdView对象
     */
    public void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 4;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; listAdapter != null && i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredWidth();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((MarginLayoutParams) params).setMargins(7, 7, 7, 7);
        // 设置参数
        listView.setLayoutParams(params);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.choise_take:
                // 点击到到该店提货
                myCallBack.click(v);
                break;
            case R.id.choise_location:
                // 点击查看地图
                myCallBack.click(v);
                break;
            default:
                break;
        }

    }

    /*
     * 回调按钮点击事件到Activity
     */
    public interface CallBack {
        public void click(View v);
    }

    class MyGridAdapter extends BaseAdapter {

        ArrayList<Value> datas;
        Context context;
        LayoutInflater inflater;

        public MyGridAdapter(ArrayList<Value> datas, Context context) {
            this.datas = datas;
            this.context = context;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return datas != null ? datas.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return datas != null && datas.size() > position ? datas
                    .get(position) : null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            try {
                GridHolder holder = new GridHolder();
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.choise_grid_item,
                            null);
                }
                holder.img = (ImageView) convertView
                        .findViewById(R.id.choise_image);
                holder.img.setLayoutParams(new LayoutParams(160, 160));
                if (position >= 0 && datas != null && position < datas.size()
                        && datas.get(position).getBigimage() != null
                        && !"".equals(datas.get(position).getBigimage())) {
//					MyApplication.loadImage(context, datas.get(position)
//							.getBigimage(), holder.img);
                    MyApplication.loadImageByPicasso(context, datas.get(position)
                            .getBigimage(), null, holder.img, 0, 0, 1);
                }
                if (convertView.getTag() == null) {
                    convertView.setTag(holder);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    /**
     * 获取每项的宽度
     *
     * @return
     */
}

class GridHolder {
    ImageView img;
}

class Holder {
    LinearLayout choise_grid_parent;
    TextView choise_shop_name;
    TextView choise_dist;
    Button choise_take;
    GridView choise_images;
    TextView choise_address;
    Button choise_location;
}
